<template>
  <div class="planMaintain">
    <el-dialog :title="option.title" :visible.sync="isShow" :close-on-click-modal="false" width="60%"
      @close="closeDialog" @open="openDialog">
      <el-card>
        <el-form :model="ruleForm" :rules="rules" size="small" label-position="left" ref="ruleForm" label-width="110px"
          class="demo-ruleForm">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="机构" prop="BRANCHNAME">
                <el-input v-model.trim="ruleForm.BRANCHNAME" size="small" :disabled="option.operation == 'edit'"
                  v-if="option.operation == 'edit'"></el-input>
                <select-tree :tree-data="treedata" :disable="disable" :branch="ruleForm.BRANCHNAME"
                  @getBranchName="getBranch" v-if="option.operation != 'edit'"></select-tree>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="option.operation == 'edit'">
              <el-form-item label="排班计划编号" prop="SPID">
                <el-input v-model.trim="ruleForm.SPID" size="small" :disabled="option.operation == 'edit'"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="排班计划名称" prop="SPNAME">
                <el-input v-model.trim="ruleForm.SPNAME" size="small" placeholder="请输入排班计划名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="周期方式" prop="PERIODTYPE">
                <el-select v-model.trim="ruleForm.PERIODTYPE" placeholder="请选择" size="small">
                  <el-option v-for="item in periodtypes" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="周数/月数" prop="PERIODNUM">
                <el-input v-model.trim="ruleForm.PERIODNUM" size="small" maxlength="2" placeholder="请输入周数/月数">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="开始日期" prop="SRTDATE">
                <el-date-picker v-model.trim="ruleForm.SRTDATE" value-format="yyyyMMdd" type="date" placeholder="选择日期"
                  size="small">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <!-- <el-col :span="12">
              <el-form-item label="人力需求编号" prop="FTEID">
                <el-select v-model="ruleForm.FTEID" placeholder="请选择" clearable collapse-tags multiple>
                  <el-option v-for="(item,index) in tableDataFTE" :key="index" :label="item.FTENAME"
                    :value="item.FTEID">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col> -->
            <!-- <el-col :span="12">
              <el-form-item label="技能" prop="SKILLFLG">
                <el-input v-model="ruleForm.SKILLFLG.join(',')" disabled></el-input>
              </el-form-item>
            </el-col> -->
            <el-col :span="24">
              <el-form-item label="人力需求" prop="FTESkill">
                <div class="block">
                  <el-cascader @change="changeVal" :options="FTESkillOption" :props="props1" v-model="ruleForm.FTESkill"
                    clearable></el-cascader>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="说明" prop="NOTES">
                <el-input type="textarea" :rows="2" v-model.trim="ruleForm.NOTES" size="small" placeholder="请输入说明">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
      <div slot="footer" class="dialog-footer">
        <el-button @click="option.isShow=false;" size="mini">取 消</el-button>
        <el-button type="primary" @click="confirmClick('ruleForm')" size="mini">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import request from "@/common/utils/requestWFM";
  import selectTree from "@/components/selectTree5/";
  import editPlanMaintain from '@/message/wfm/intelligenceSchedule/planMaintain/editPlanMaintain';
  import addPlanMaintain from '@/message/wfm/intelligenceSchedule/planMaintain/addPlanMaintain';
  // import FTEQuery from '@/message/wfm/intelligenceSchedule/FTEMaintain/FTEQuery';
  // import dataQuery from '@/message/wfm/baseData/dictionaryManage/dictionaryQuery';
  import FQuery from '@/message/wfm/intelligenceSchedule/FTEMaintain/FTEQuery'

  export default {
    props: {
      option: Object
    },
    components: {
      selectTree
    },
    data() {
      return {
        FTESkillOption: [],
        FTEOption: [], //人力需求
        skillOption: [], //坐席技能
        props1: {
          multiple: true
        },
        options: [{
          value: 1,
          label: '东南',
          children: [{
              value: 2,
              label: '上海',
            }, {
              value: 7,
              label: '江苏',
            },
            {
              value: 12,
              label: '浙江',
            }
          ]
        }, {
          value: 17,
          label: '西北',
          children: [{
            value: 18,
            label: '陕西'
          }, {
            value: 21,
            label: '新疆维吾尔族自治区',

          }]
        }],
        disable: false,
        ruleForm: {
          FTESkill: [],
          BRANCHNAME: '',
          BRANCHNO: '',
          SPID: '',
          SPNAME: '',
          NOTES: '',
          PERIODTYPE: '',
          PERIODNUM: '',
          SRTDATE: '',
          FTEID: [],
          SKILLFLG: [],
        },
        rules: {
          SPNAME: [{
            required: true,
            message: '请输入排班计划名称',
            trigger: 'blur'
          }],
          BRANCHNAME: [{
            required: true,
            message: '请选择机构',
            trigger: 'change'
          }],
          PERIODNUM: [{
            required: true,
            message: '请输入周数/月数',
            trigger: 'blur'
          }],
          SRTDATE: [{
            required: true,
            message: '请选择开始日期',
            trigger: 'change'
          }],
          PERIODTYPE: [{
            required: true,
            message: '请选择周期方式',
            trigger: 'change'
          }],
        },
        periodtypes: [{
          value: 'week',
          label: '周'
        }, {
          value: 'month',
          label: '月'
        }, ],
        PERIODTYPE: '',
        treedata: [],
        // tableDataFTE: [],
        // SKILLFLGS: [],
      }
    },
    computed: {
      isShow: {
        get() {
          return this.option.isShow;
        },
        set(value) {
          this.option.isShow = value;
        }
      }
    },
    watch: {
      'ruleForm.FTESkill'(val) {
        // console.log(val)
      }
    },
    mounted() {},
    methods: {
      // 人力需求查询
      async FTEQuery() {
        let resBody = new FQuery()
        resBody.data.BRANCHNO = this.ruleForm.BRANCHNO
        let response = await request(resBody);
        if (response.SYS_HEAD.ReturnCode == "000000") {
          this.FTEOption = response.BODY.RSPSTRUCT;
          let outArr = []
          let insideArr = []
          if (this.FTEOption == undefined || this.FTEOption.length == 0) {
            this.$message.error('该机构下没有人力需求，请先配置人力需求')
            this.FTESkillOption = []
            return false
          }
          this.FTEOption.forEach(item => {
            insideArr.push({
              value: item.FTEID,
              label: item.FTENAME,
              skill: item.SKILLFLG
            })
          })
          this.option.skillOption.forEach(item => {
            outArr.push({
              value: item.FIELDKEY,
              label: item.FIELDVALUE,
              children: this.findName(insideArr, item.FIELDKEY)
            })
          })
          this.FTESkillOption = outArr
        } else {
          this.$message({
            type: "error",
            message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD.ReturnMessage
          })
        }
      },
      findName(arr, val) {
        let data = arr.filter(item => {
          return item.skill == val
        })
        if (data.length)
          return data
      },
      changeVal(val) {
        if (val == undefined) return
        this.ruleForm.FTESkill = val
        if (val.length == 1) return
        let arr = []
        this.ruleForm.FTESkill.forEach(item => {
          arr.push(item[0])
        })
        let flag = this.isRepeat(arr)
        if (flag == true) {
          this.$message.error('每个技能下只能选择一个人力需求！请重新选择')
          this.$forceUpdate()
          return
        }
        this.$forceUpdate()

        // let arr1 = []
        // var obj = {};
        // this.ruleForm.FTESkill = this.ruleForm.FTESkill.reduce((item, next) =>{
        //   obj[next[0]] ? '' : obj[next[0]] = true && item.push(next);
        //   return item;
        // }, [])

        // this.ruleForm.FTESkill = arr1
        // val = arr1
        // console.log(this.ruleForm.FTESkill )
      },
      isRepeat(arr) {
        let hash = {};
        for (let i in arr) {
          if (hash[arr[i]]) {
            return true;
          }
          hash[arr[i]] = true;
        }
        return false;
      },
      getBranch(data) {
        this.ruleForm.FTEID = [];
        this.ruleForm.BRANCHNO = data.BRANCHNO
        this.ruleForm.BRANCHNAME = data.BRANCHNAME
        this.FTEQuery();
      },
      openDialog() {
        if (this.$refs['ruleForm'] != undefined) {
          this.$refs['ruleForm'].clearValidate();
        }
        this.FTESkillOption = JSON.parse(JSON.stringify(this.option.options));
        if (this.option.operation == 'edit') {
          this.ruleForm = JSON.parse(JSON.stringify(this.option.row));
          this.disable = true;
          let arr = []
          this.option.tableData.forEach(item => {
            if (item.SPID == this.ruleForm.SPID) {
              arr.push([
                item.SKILLFLG, item.FTEID
              ])
            }
          })
          this.ruleForm.FTESkill = JSON.parse(JSON.stringify(arr));
          // if (this.ruleForm.FTEID) {
          //   // this.$parent.$parent.queryPlanMaintain(this.ruleForm.SPID);
          // }
        }
      },
      getData(val) {
        this.ruleForm.SKILLFLG = [];
        this.ruleForm.FTEID = [];
        val.forEach(item => {
          if (item.SKILLFLG) {
            this.ruleForm.SKILLFLG.push(item.SKILLFLG);
          }
          if (item.FTEID) {
            this.ruleForm.FTEID.push(item.FTEID);
          }
        })
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
        this.$refs['ruleForm'].clearValidate();
      },
      confirmClick(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let arr = []
            this.ruleForm.FTESkill.forEach(item => {
              arr.push(item[0])
            })
            let flag = this.isRepeat(arr)
            if (flag == true) {
              this.$message.error('每个技能下只能选择一个人力需求！请重新选择')
              return
            }
            if (this.option.operation == 'edit') {
              this.editPlanMaintain();
            } else if (this.option.operation == 'add') {
              this.addPlanMaintain();
            }
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      //关闭弹窗
      closeDialog() {
        // this.tableDataFTE = [];
        this.ruleForm = {
          FTESkill: [],
          BRANCHNAME: '',
          BRANCHNO: '',
          SPNAME: '',
          NOTES: '',
          PERIODTYPE: '',
          PERIODNUM: '',
          SRTDATE: '',
          FTEID: [],
        };
        this.disable = false
        if (this.$refs['ruleForm'] != undefined) {
          this.$refs['ruleForm'].resetFields();
          this.$refs['ruleForm'].clearValidate();
        }
      },
      // 编辑
      async editPlanMaintain() {
        this.loading = true;
        let STRUCT = []
        if (this.ruleForm.FTESkill == undefined || this.ruleForm.FTESkill.length == 0) {
          this.$message.error('请选择技能以及对应的人力需求编号！')
          return false
        }
        this.ruleForm.FTESkill.forEach(item => {
          STRUCT.push({
            FTEID: item[1],
            SKILLFLG: item[0]
          })
        })
        let resBody = new editPlanMaintain();
        resBody.data.BRANCHNO = this.ruleForm.BRANCHNO
        resBody.data.SPNAME = this.ruleForm.SPNAME;
        resBody.data.SRTDATE = this.ruleForm.SRTDATE;
        resBody.data.SPID = this.ruleForm.SPID;
        resBody.data.NOTES = this.ruleForm.NOTES;
        resBody.data.PERIODTYPE = this.ruleForm.PERIODTYPE;
        resBody.data.PERIODNUM = this.ruleForm.PERIODNUM;
        resBody.data.STRUCT = STRUCT;
        let response = await request(resBody);
        if (response.SYS_HEAD.ReturnCode == "000000") {
          this.$parent.$parent.queryPlanMaintain();
          this.option.isShow = false;
          this.$message({
            type: "success",
            message: "修改成功"
          });
        } else {
          this.$message({
            type: "error",
            message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD.ReturnMessage
          });
        }
        this.loading = false;
      },
      // 新增
      async addPlanMaintain() {
        this.loading = true;
        let STRUCT = []
        if (this.ruleForm.FTESkill == undefined || this.ruleForm.FTESkill.length == 0) {
          this.$message.error('请选择技能以及对应的人力需求编号！')
          return false
        }
        this.ruleForm.FTESkill.forEach(item => {
          STRUCT.push({
            FTEID: item[1],
            SKILLFLG: item[0]
          })
        })
        let resBody = new addPlanMaintain();
        resBody.data.BRANCHNO = this.ruleForm.BRANCHNO
        resBody.data.SPNAME = this.ruleForm.SPNAME;
        resBody.data.SRTDATE = this.ruleForm.SRTDATE;
        resBody.data.NOTES = this.ruleForm.NOTES;
        resBody.data.PERIODTYPE = this.ruleForm.PERIODTYPE;
        resBody.data.PERIODNUM = this.ruleForm.PERIODNUM;
        resBody.data.STRUCT = STRUCT;
        let response = await request(resBody);
        if (response.SYS_HEAD.ReturnCode == "000000") {
          this.$parent.$parent.queryPlanMaintain();
          this.option.isShow = false;
          this.$message({
            type: "success",
            message: "保存成功"
          });
        } else {
          this.$message({
            type: "error",
            message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD.ReturnMessage
          });
        }
        this.loading = false;
      },
      // // 技能参数查询
      // async dataDictionaryQuery() {
      //   let resBody = new dataQuery();
      //   resBody.data.FIELDCODE = 'AGENTSKILL';
      //   resBody.data.FIELDNAME = '';
      //   resBody.data.CurrPage = 1;
      //   resBody.data.PageRowNum = 100;
      //   let response = await request(resBody);
      //   if (response.SYS_HEAD.ReturnCode == "000000") {
      //     this.SKILLFLGS = response.BODY.FIEDATA;
      //   } else {
      //     this.$message({
      //       type: "error",
      //       message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD.ReturnMessage
      //     })
      //   }
      // },
      // 人力需求查询
      // async FTEQuery() {
      //   let resBody = new FTEQuery()
      //   resBody.data.BRANCHNO = this.ruleForm.BRANCHNO;
      //   resBody.data.FTEID = '';
      //   resBody.data.FTENAME = '';
      //   let response = await request(resBody);
      //   if (response.SYS_HEAD.ReturnCode == "000000") {
      //     this.tableDataFTE = response.BODY.RSPSTRUCT;
      //   } else {
      //     this.$message({
      //       type: "error",
      //       message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD.ReturnMessage
      //     })
      //   }
      // },
    }
  };

</script>

<style lang="scss">
  .planMaintain {
    .el-input {
      width: 100%;
    }

  }

</style>

<style scoped lang="scss">

</style>
